<template>

  <div style="margin-top: 20px;">
    <el-row style="justify-content: space-around;"
      :style="userStore.isMobile ? 'display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;' : ''">

      <el-card :style="userStore.isMobile ? 'width: 100%; margin: 0;' : 'width: 11vw; cursor: pointer;'"
        @click="openDrawer('pre')">
        <div
          style="display: flex; flex-direction: column; font-size: 14px; color: var(--el-text-color-regular); font-weight: bold;">
          <span style="display: flex; justify-content: space-between; align-items: center; padding-top: 0px;">
            <span>
              立项前期
              <el-tag type="primary">
                {{ phaseDatas?.pre }}
              </el-tag>
            </span>
            <el-icon style="cursor: pointer;" @click.stop="openDrawer('pre')">
              <ArrowRight />
            </el-icon>
          </span>
        </div>
      </el-card>

      <el-card :style="userStore.isMobile ? 'width: 100%; margin: 0;' : 'width: 11vw; cursor: pointer;'"
        @click="openDrawer('impl')">
        <div
          style="display: flex; flex-direction: column; font-size: 14px; color: var(--el-text-color-regular); font-weight: bold;">
          <span style="display: flex; justify-content: space-between; align-items: center; padding-top: 0px;">
            <span>
              项目实施
              <el-tag type="primary">
                {{ phaseDatas?.impl }}
              </el-tag>
            </span>
            <el-icon style="cursor: pointer;" @click.stop="openDrawer('impl')">
              <ArrowRight />
            </el-icon>
          </span>
        </div>
      </el-card>

      <el-card :style="userStore.isMobile ? 'width: 100%; margin: 0;' : 'width: 11vw; cursor: pointer;'"
        @click="openDrawer('accept')">
        <div
          style="display: flex; flex-direction: column; font-size: 14px; color: var(--el-text-color-regular); font-weight: bold;">
          <span style="display: flex; justify-content: space-between; align-items: center; padding-top: 0px;">
            <span>
              项目验收
              <el-tag type="primary">
                {{ phaseDatas?.accept }}
              </el-tag>
            </span>
            <el-icon style="cursor: pointer;" @click.stop="openDrawer('accept')">
              <ArrowRight />
            </el-icon>
          </span>
        </div>
      </el-card>

      <el-card :style="userStore.isMobile ? 'width: 100%; margin: 0;' : 'width: 11vw; cursor: pointer;'"
        @click="openDrawer('accounting')">
        <div
          style="display: flex; flex-direction: column; font-size: 14px; color: var(--el-text-color-regular); font-weight: bold;">
          <span style="display: flex; justify-content: space-between; align-items: center; padding-top: 0px;">
            <span>
              项目核算
              <el-tag type="primary">
                {{ phaseDatas?.accounting }}
              </el-tag>
            </span>
            <el-icon style="cursor: pointer;" @click.stop="openDrawer('accounting')">
              <ArrowRight />
            </el-icon>
          </span>
        </div>
      </el-card>

      <el-card :style="userStore.isMobile ? 'width: 100%; margin: 0;' : 'width: 11vw; cursor: pointer;'"
        @click="openDrawer('warranty')">
        <div
          style="display: flex; flex-direction: column; font-size: 14px; color: var(--el-text-color-regular); font-weight: bold;">
          <span style="display: flex; justify-content: space-between; align-items: center; padding-top: 0px;">
            <span>
              项目质保
              <el-tag type="primary">
                {{ phaseDatas?.warranty }}
              </el-tag>
            </span>
            <el-icon style="cursor: pointer;" @click.stop="openDrawer('warranty')">
              <ArrowRight />
            </el-icon>
          </span>
        </div>
      </el-card>

      <el-card :style="userStore.isMobile ? 'width: 100%; margin: 0;' : 'width: 11vw; cursor: pointer;'"
        @click="openDrawer('complete')">
        <div
          style="display: flex; flex-direction: column; font-size: 14px; color: var(--el-text-color-regular); font-weight: bold;">
          <span style="display: flex; justify-content: space-between; align-items: center; padding-top: 0px;">
            <span>
              项目归档
              <el-tag type="primary">
                {{ phaseDatas?.complete }}
              </el-tag>
            </span>
            <el-icon style="cursor: pointer;" @click.stop="openDrawer('complete')">
              <ArrowRight />
            </el-icon>
          </span>
        </div>
      </el-card>
    </el-row>
    <!-- -->
    <div>
      <el-row :gutter="20" :style="userStore.isMobile ? 'padding: 10px;' : 'padding: 10px 20px;'">
        <el-card class="box-card" style="width: 100%;" v-if="indexPer">
          <template #header>
            <div class="card-header"
              :style="userStore.isMobile ? 'flex-direction: column; align-items: flex-start; gap: 10px;' : ''">
              <span>需我处理的项目</span>
              <el-button class="button" text>
                <div :style="userStore.isMobile ? 'margin-left: 0; width: 100%;' : 'margin-left: 0px;'">
                  <el-select @change="handleSelectionChange" v-model="queryParamsneed.phaseId" placeholder="请选择环节"
                    clearable :style="userStore.isMobile ? 'width: 120px;' : 'width: 200px'">
                    <el-option v-for="dict in select_phase" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </div>
              </el-button>
            </div>
          </template>
          <div class="text item">
            <div style="justify-content: flex-start;" v-if="userStore.name == 'xuhb'">
              <el-checkbox-group v-model="selectedProps"
                :style="userStore.isMobile ? 'display: flex; flex-wrap: wrap; gap: 5px;' : ''">
                <el-checkbox v-for="col in allColumns" :key="col.prop" :label="col.prop">
                  {{ col.label }}
                </el-checkbox>
              </el-checkbox-group>
              <el-button type="primary" plain style="margin: 10px;" @click="saveColumnConfig">保存配置</el-button>
            </div>

            <el-table v-loading="loading" :data="need" border
              :style="userStore.isMobile ? 'width: 100%; overflow-x: auto;' : ''">
              <el-table-column v-for="col in visibleColumns" :key="col.prop" :prop="col.prop" :label="col.label"
                :align="'center'"
                :show-overflow-tooltip="['projectName', 'createUserName', 'contractAmount', 'settlementAmount', 'phaseName', 'approvalDate', 'updateTime', 'acceptTime', 'customerName', 'housekeeperName', 'projectTypeName', 'joinPeople', 'currentPeople'].includes(col.prop)"
                :width="getWidth(col.prop)">
                <template #default="scope" v-if="['approvalDate', 'planDate', 'acceptTime'].includes(col.prop)">
                  <span>{{ parseTime(scope.row[col.prop], "{y}-{m}-{d}") }}</span>
                </template>
              </el-table-column>

              <el-table-column label="操作" fixed="right" :width="userStore.isMobile ? '100' : '220'" align="center">
                <template #default="scope">
                  <el-button link type="primary" icon="View" :style="userStore.isMobile ? 'padding: 5px;' : ''"
                    @click="handleView(scope.row)">查看</el-button>
                  <el-button link type="primary" icon="Edit" :style="userStore.isMobile ? 'padding: 5px;' : ''"
                    @click="goto(scope.row)">去处理</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination :autoScroll="false" v-show="needTotal > 0" :total="needTotal"
              v-model:page="queryParamsneed.pageNum" v-model:limit="queryParamsneed.pageSize" @pagination="getListNeed"
              :small="userStore.isMobile" />
          </div>
        </el-card>
      </el-row>

      <el-row v-if="userStore.name == 'wuzg'" :gutter="10"
        style="padding-left: 5px;padding-right: 5px;padding-top: 5px;">
        <el-card class="box-card" style="width: 100%;" v-if="indexPer">
          <template #header>
            <div class="card-header" style="font-size: 14px;">
              <span style="font-size: 15px; font-weight: 500;">待审核的往来客户</span>
              <el-button class="button" text size="small">
              </el-button>
            </div>
          </template>
          <div class="text item">
            <el-table v-loading="loading" border :data="customerList" @selection-change="handleSelectionChange"
              :style="userStore.isMobile ? 'width: 100%; overflow-x: auto;' : ''">
              <el-table-column label="客户名称" align="center" show-overflow-tooltip width="120" prop="customerName" />
              <el-table-column label="起始日期" align="center" show-overflow-tooltip width="90" prop="startDate">
                <template #default="scope">
                  <span style="font-size: 12px;">{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="截至日期" show-overflow-tooltip align="center" width="90" prop="endDate">
                <template #default="scope">
                  <span style="font-size: 12px;">{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="发起人" show-overflow-tooltip align="center" width="80" prop="promoterName" />
              <el-table-column label="状态" show-overflow-tooltip align="center" width="80" prop="status">
                <template #default="scope">
                  <dict-tag type="primary" :options="audit_type" :value="scope.row.status" />
                </template>
              </el-table-column>
              <el-table-column label="操作" show-overflow-tooltip align="center" width="80"
                class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link type="primary" icon="Edit" size="small"
                    @click="gotoCustomer(scope.row, 'edit')">处理</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-row>

      <el-row :gutter="10" style="padding-left: 8px;padding-right: 8px;padding-top: 8px;">
        <el-card class="box-card" style="width: 100%;">
          <template #header>
            <div class="card-header" style="font-size: 14px; line-height: 1.5;">
              <span style="font-size: 15px; font-weight: 500;">我发起的项目</span>
              <el-button type="primary" style="margin-left: 20px;" icon="plus" @click="addProject()">新增项目</el-button>
            </div>
          </template>
          <div class="text item" style="overflow-x: auto;">
            <div style="justify-content: flex-start;" v-if="userStore.name == 'xuhb'">
              <el-checkbox-group v-model="selectedProps"
                :style="userStore.isMobile ? 'display: flex; flex-wrap: wrap; gap: 5px;' : ''">
                <el-checkbox v-for="col in allColumns" :key="col.prop" :label="col.prop">
                  {{ col.label }}
                </el-checkbox>
              </el-checkbox-group>
              <el-button type="primary" plain style="margin: 10px;" @click="saveColumnConfig">保存配置</el-button>
            </div>

            <el-table v-loading="loading" :data="myList" border>
              <el-table-column v-for="col in visibleColumns" :key="col.prop" :prop="col.prop" :label="col.label"
                :align="'center'"
                :show-overflow-tooltip="['projectName', 'createUserName', 'contractAmount', 'settlementAmount', 'phaseName', 'approvalDate', 'updateTime', 'acceptTime', 'customerName', 'housekeeperName', 'projectTypeName', 'joinPeople', 'currentPeople'].includes(col.prop)"
                :width="getWidth(col.prop)" :header-cell-style="{ padding: '5px 0', fontSize: '12px' }"
                :cell-style="{ padding: '5px 0', fontSize: '12px' }">
                <template #default="scope" v-if="['approvalDate', 'planDate', 'acceptTime'].includes(col.prop)">
                  <span style="font-size: 12px;">{{ parseTime(scope.row[col.prop], "{y}-{m}-{d}") }}</span>
                </template>
              </el-table-column>

              <el-table-column label="操作" fixed="right" width="100" align="center"
                :header-cell-style="{ padding: '5px 0', fontSize: '12px' }"
                :cell-style="{ padding: '5px 0', fontSize: '12px' }">
                <template #default="scope">
                  <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination :autoScroll="false" v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize" @pagination="getListCreate"
              style="margin-top: 10px; --el-pagination-font-size: 12px;" :small="true" />
          </div>
        </el-card>
      </el-row>



      <el-row :gutter="10" style="padding-left: 8px;padding-right: 8px;padding-top: 8px;">
        <el-card class="box-card" style="width: 100%;">
          <template #header>
            <div class="card-header"
              style="display: flex; justify-content: start; align-items: center; font-size: 14px;">
              <span style="font-size: 15px; font-weight: 500;">配合项目</span>
              <el-button @click="gotoJoin(4)" class="button" text
                style="padding: 0; font-size: 16px;margin-left: 10px;margin-top: 2px;">
                更多
                <el-icon style="cursor: pointer; vertical-align: middle;">
                  <ArrowRight />
                </el-icon>
              </el-button>
              <el-button type="primary" style="margin-left: 20px;" icon="plus" @click="addProject()">新增项目</el-button>

            </div>
          </template>
          <div class="text item" style="overflow-x: auto;">
            <div style="justify-content: flex-start;" v-if="userStore.name == 'xuhb'">
              <el-checkbox-group v-model="selectedProps"
                :style="userStore.isMobile ? 'display: flex; flex-wrap: wrap; gap: 5px;' : ''">
                <el-checkbox v-for="col in allColumns" :key="col.prop" :label="col.prop">
                  {{ col.label }}
                </el-checkbox>
              </el-checkbox-group>
              <el-button type="primary" plain style="margin: 10px;" @click="saveColumnConfig">保存配置</el-button>
            </div>

            <el-table v-loading="loading" :data="assistList" border>
              <el-table-column v-for="col in visibleColumns" :key="col.prop" :prop="col.prop" :label="col.label"
                :align="'center'"
                :show-overflow-tooltip="['projectName', 'createUserName', 'contractAmount', 'settlementAmount', 'phaseName', 'approvalDate', 'updateTime', 'acceptTime', 'customerName', 'housekeeperName', 'projectTypeName', 'joinPeople', 'currentPeople'].includes(col.prop)"
                :width="getWidth(col.prop)" :header-cell-style="{ padding: '5px 0', fontSize: '12px' }"
                :cell-style="{ padding: '5px 0', fontSize: '12px' }">
                <template #default="scope" v-if="['approvalDate', 'planDate', 'acceptTime'].includes(col.prop)">
                  <span style="font-size: 12px;">{{ parseTime(scope.row[col.prop], "{y}-{m}-{d}") }}</span>
                </template>
              </el-table-column>

              <el-table-column label="操作" fixed="right" width="100" align="center"
                :header-cell-style="{ padding: '5px 0', fontSize: '12px' }"
                :cell-style="{ padding: '5px 0', fontSize: '12px' }">
                <template #default="scope">
                  <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
                  <el-button link type="primary" icon="Edit" @click="goto(scope.row)">去处理</el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination :autoScroll="false" v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize" @pagination="getListCreate"
              style="margin-top: 10px; --el-pagination-font-size: 12px;" :small="true" />
          </div>
        </el-card>
      </el-row>

      <el-row :gutter="10" style="padding-left: 8px;padding-right: 8px;padding-top: 8px;">
        <el-card class="box-card" style="width: 100%;">
          <template #header>
            <div class="card-header"
              style="display: flex; justify-content: start; align-items: center; font-size: 14px;">
              <span style="font-size: 15px; font-weight: 500;">我参与的项目</span>
              <el-button @click="gotoJoin(1)" class="button" text
                style="padding: 0; font-size: 16px;margin-left: 10px;margin-top: 2px;">
                更多
                <el-icon style="cursor: pointer; vertical-align: middle;">
                  <ArrowRight />
                </el-icon>
              </el-button>
            </div>
          </template>
          <div class="text item" style="overflow-x: auto;">
            <div style="justify-content: flex-start;" v-if="userStore.name == 'xuhb'">
              <el-checkbox-group v-model="selectedProps"
                :style="userStore.isMobile ? 'display: flex; flex-wrap: wrap; gap: 5px;' : ''">
                <el-checkbox v-for="col in allColumns" :key="col.prop" :label="col.prop">
                  {{ col.label }}
                </el-checkbox>
              </el-checkbox-group>
              <el-button type="primary" plain style="margin: 10px;" @click="saveColumnConfig">保存配置</el-button>
            </div>

            <el-table v-loading="loading" :data="completeList" border>
              <el-table-column v-for="col in visibleColumns" :key="col.prop" :prop="col.prop" :label="col.label"
                :align="'center'"
                :show-overflow-tooltip="['projectName', 'createUserName', 'contractAmount', 'settlementAmount', 'phaseName', 'approvalDate', 'updateTime', 'acceptTime', 'customerName', 'housekeeperName', 'projectTypeName', 'joinPeople', 'currentPeople'].includes(col.prop)"
                :width="getWidth(col.prop)" :header-cell-style="{ padding: '5px 0', fontSize: '12px' }"
                :cell-style="{ padding: '5px 0', fontSize: '12px' }">
                <template #default="scope" v-if="['approvalDate', 'planDate', 'acceptTime'].includes(col.prop)">
                  <span style="font-size: 12px;">{{ parseTime(scope.row[col.prop], "{y}-{m}-{d}") }}</span>
                </template>
              </el-table-column>

              <el-table-column label="操作" fixed="right" width="100" align="center"
                :header-cell-style="{ padding: '5px 0', fontSize: '12px' }"
                :cell-style="{ padding: '5px 0', fontSize: '12px' }">
                <template #default="scope">
                  <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
                  <el-button link type="primary" icon="Edit" @click="goto(scope.row)">去处理</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-row>


      <el-dialog v-model="openView" fullscreen append-to-body>
        <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="项目信息" name="first">
            <projectView :key="'projectView' + form.projectNo" :datas="form" :isView="isView" :column="3"
              :sizes="'large'" :personList="personList" :attachmentList="attachmentList" :payList="payList"
              :warrantyList="warrantyList" :implementList="implementList" :accountingList="accountingList">
            </projectView>
          </el-tab-pane>
          <el-tab-pane label="正式清单" name="second">
            <mainList v-if="activeName == 'second'" :datas="form"></mainList>
          </el-tab-pane>
          <el-tab-pane label="管家婆出库单" name="third">
            <saleList v-if="activeName == 'third'" :datas="form"></saleList>
          </el-tab-pane>
          <el-tab-pane label="费用汇总" name="four">
            <feeList v-if="activeName == 'four'" :datas="form"></feeList>
          </el-tab-pane>
          <el-tab-pane label="清单对比" name="five">
            <compareMainAndSale v-if="activeName == 'five'" :datas="form"></compareMainAndSale>
          </el-tab-pane>
          <el-tab-pane label="配套施工清单" name="seven">
            <matching v-if="activeName == 'seven'" :datas="form"></matching>
          </el-tab-pane>
        </el-tabs>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="cancel">关 闭</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

  </div>



</template>

<script setup>
import {
  ArrowRight,
} from '@element-plus/icons-vue'
import {
  getProject, listPhase, listAccounting, getPostPermissions, getMyListProcessing, myJoinProject, needHandle, myAccountingList,
  listParticipan, getPermission, getPermissionIndex, listImplement, getResults, myProject, listAttachment, listPay, listWarranty, listProject,
  saveUserTableConfig, getUserTableConfig, overTimeList, getAssistList
} from "@/api/project/project";


import { auditList } from "@/api/project/customer";

import projectView from "./project/projectView.vue";

const { proxy } = getCurrentInstance();
const myList = ref([]);
const assistList = ref([]);
const overTime = ref([]);
const completeList = ref([]);
const notifyList = ref([]);
const need = ref([]);
const customerList = ref([])
const indexPer = ref("false")
const { project_type } = proxy.useDict("project_type");
const attachmentList = ref([]);
const payList = ref([]);
const personList = ref([]);
const accountingList = ref([]);
const implementList = ref([]);
const logs = ref([]);
const warrantyList = ref([]);
const openView = ref(false);
const isView = ref(false);
const ids = ref([]);
const projectNo = ref("")
const finance = ref(false);//当期人员是否是财务
const isAdmin = ref(false);//是否是超级管理员
const havePay = ref(false);//是否有添加付款信息的权限
const status = ref("0");
const formDisabled = ref(true);
const loading = ref(true);
const total = ref(0);
const assistTotal = ref(0)
const isImplementPer = ref(false);//当期人员是否是施工
const completeTotal = ref(0);
const needTotal = ref(0)

const phaseDatas = ref({})
// 表单重置
function reset() {
  form.value = {
  };
  proxy.resetForm("projectRef");
}

const data = reactive({
  currentProject: {},
  form: {
    createUserName: null,
    createUserId: null,
    createDeptName: null,
    createDept: null,
  },
  personForm: {
  },
  fileForm: {

  },
  warrantyForm: {

  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // status: 2,//写死 查询上个阶段已完成的项目 1是进行中 2是已完成 
    // 新建项目的时候会默认插入一条立项阶段到立项表 点击下一步的时候会更新阶段表把当前项目当前阶段的状态
    //改为已完成  同时往阶段表插入下一个阶段 状态是1 进行中
    // phaseId: 5,//阶段字典id 查询已归档
    projectName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerName: null,
    housekeeperName: null,
    phaseCode: null,
    minProjectAmount: null,
    maxProjectAmount: null
  },
  queryParamsCom: {
    pageNum: 1,
    pageSize: 5,
    // status: 2,//写死 查询上个阶段已完成的项目 1是进行中 2是已完成 
    // 新建项目的时候会默认插入一条立项阶段到立项表 点击下一步的时候会更新阶段表把当前项目当前阶段的状态
    //改为已完成  同时往阶段表插入下一个阶段 状态是1 进行中
    // phaseId: 5,//阶段字典id 查询已归档
    projectName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerName: null,
    housekeeperName: null,
    phaseCode: null,
    minProjectAmount: null,
    maxProjectAmount: null
  },
  queryParamsneed: {
    pageNum: 1,
    pageSize: 10,
    // status: 2,//写死 查询上个阶段已完成的项目 1是进行中 2是已完成 
    // 新建项目的时候会默认插入一条立项阶段到立项表 点击下一步的时候会更新阶段表把当前项目当前阶段的状态
    //改为已完成  同时往阶段表插入下一个阶段 状态是1 进行中
    phaseId: null,//阶段字典id 查询已归档
    projectName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerName: null,
    housekeeperName: null,
    phaseCode: null,
    minProjectAmount: null,
    maxProjectAmount: null
  },
  rules: {
    projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
    approvalDate: [{ required: true, message: "立项日期不能为空", trigger: "blur" }],
    projectType: [{ required: true, message: "项目类型 不能为空", trigger: "blur" }],
  },

  warrantyRules: {
    company: [{ required: true, message: "付款单位不能为空", trigger: "blur" }],
    settlementAmount: [{ required: true, message: "结算金额不能为空", trigger: "blur" }],
    settlementAmount: [{ required: true, message: "结算金额不能为空,请联系负责人在项目信息中填写结算金额", trigger: "blur" }],
  },

  result: {

  }

});

const { queryParams, queryParamsCom, queryParamsneed, form, personForm, payRules, warrantyRules, fileForm, warrantyForm, result } = toRefs(data);



import mainList from "./project/mainList.vue";
import saleList from "./project/saleList.vue";
import feeList from "./project/fee.vue"
import compareMainAndSale from "./project/compareMainAndSale.vue"
import matching from "../views/project/matching.vue"

const activeName = ref('first')
function handleClick(item, event) {
  // activeName
  console.log("tabs页面跳转", item.paneName, event)
  activeName.value = item.paneName
}


async function handleView(row) {
  activeName.value = "first"
  formDisabled.value = true
  isView.value = true
  reset();
  getInfo(row.projectNo)
  const _projectNo = row.projectNo || ids.value;
  await getProject(_projectNo).then((response) => {
    form.value = response.data;
    openView.value = true;
  });

}

import { useRouter } from 'vue-router';
import { ref } from 'vue';

const router = useRouter();


function addProject() {
  router.push({
    path: '/project/projectManage',
    query: { add: 'add' } // URL 参数：/user?id=123
  });
}

async function handleOper(row) {
  projectNo.value = row.projectNo
  await isImplement();
  if (isImplementPer.value && row.phaseId != "2") { //施工人员  且跳转处理的不是施工 
    proxy.$modal.msgError("暂无权限");
    return
  }

  if (isImplementPer.value && row.phaseId != "2") { //施工人员  且跳转处理的不是施工 
    proxy.$modal.msgError("暂无权限");
    return
  }

  if (row.phaseId == "0") {//项目立项
    router.push({
      path: '/project/projectManage',
      // query: { row: row } // URL 参数：/user?id=123
    });

  } else if (row.phaseId == "1") {//立项前期
    router.push({
      path: '/approve/projecPreMange',
      // query: { row: row } // URL 参数：/user?id=123
    });

  } else if (row.phaseId == "2") {//项目实施
    router.push({
      path: '/implement/projectImplement',
      // query: { row: row } // URL 参数：/user?id=123
    });

  }
  else if (row.phaseId == "8") {//项目验收
    router.push({
      path: '/accept/projectAccept',
      // query: { row: row } // URL 参数：/user?id=123
    });

  }
  else if (row.phaseId == "7") {//项目核算
    router.push({
      path: '/projectAccounting/accounting',
      // query: { row: row } // URL 参数：/user?id=123
    });

  } else if (row.phaseId == "5") {//项目质保
    router.push({
      path: '/warranty/projectWarranty',
      // query: { row: row } // URL 参数：/user?id=123
    });

  } else if (row.phaseId == "6") {//项目归档
    router.push({
      path: '/complete/projectWait',
      // query: { row: row } // URL 参数：/user?id=123
    });

  }

}

function gotoJoin(type) {
  router.push({
    path: '/myJoin/myProject',
    query: { type: type } // URL 参数：/user?id=123
  });
}

function gotoCustomer(row) {
  router.push({
    path: '/customer/waitAudit',
    // query: { row: row } // URL 参数：/user?id=123
  });
}


function goto(row) {
  console.log("首页跳转", row);
  if (row.phaseId == "2") {//立项前期
    router.push({
      path: '/approve/projecPreMange',
      query: { projectNo: row.projectNo }
    });

  } if (row.phaseId == "3") {//项目实施
    router.push({
      path: '/implement/projectImplement',
      query: { projectNo: row.projectNo }
    });

  }
  else if (row.phaseId == "4") {//项目验收
    router.push({
      path: '/accept/projectAccept',
      query: { projectNo: row.projectNo }
    });

  }
  else if (row.phaseId == "5") {//项目核算
    router.push({
      path: '/projectAccounting/accounting',
      query: { projectNo: row.projectNo }
    });

  } else if (row.phaseId == "6") {//项目质保
    router.push({
      path: '/warranty/projectWarranty',
      query: { projectNo: row.projectNo }
    });

  } else if (row.phaseId == "7") {//项目归档
    router.push({
      path: '/complete/projectWait',
      query: { projectNo: row.projectNo }
    });
  }
  else if (row.phaseId == "1") {//项目立项
    router.push({
      path: '/project/projectManage',
      query: {
        projectNo: row.projectNo,
      }
    });
  }

}

function openDrawer(type) {
  console.log("", type);


  if (type == "pre") {//立项前期
    router.push({
      path: '/approve/projecPreMange',
      // query: { row: row } // URL 参数：/user?id=123
    });

  } else if (type == "impl") {//项目实施
    router.push({
      path: '/implement/projectImplement',
      // query: { row: row } // URL 参数：/user?id=123
    });

  }
  else if (type == "accept") {//项目验收
    router.push({
      path: '/accept/projectAccept',
      // query: { row: row } // URL 参数：/user?id=123
    });

  }
  else if (type == "accounting") {//项目核算
    router.push({
      path: '/projectAccounting/accounting',
      // query: { row: row } // URL 参数：/user?id=123
    });

  } else if (type == "warranty") {//项目质保
    router.push({
      path: '/warranty/projectWarranty',
      // query: { row: row } // URL 参数：/user?id=123
    });

  } else if (type == "complete") {//项目归档
    router.push({
      path: '/complete/projectWait',
      // query: { row: row } // URL 参数：/user?id=123
    });
  }

}

const { select_phase } = proxy.useDict('select_phase');


// 取消按钮
function cancel() {
  openView.value = false
  //   reset();
}

//是否是财务
async function isFinance() {
  let params = {
    projectNo: projectNo.value,
    // phaseId: 1,//立项前期 写死
    postIds: [2, 6]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  finance.value = await hasPermisson(params)
  console.log("添加财务信息", finance.value);
}

async function hasPermisson(params) {
  const res = await getPermission(params).then((response) => {
    console.log("权限信息", response.data);
    return response.data
  });
  return res
}


async function hasPermissonPost(params) {
  const res = await getPostPermissions(params).then((response) => {
    console.log("权限信息", response.data);
    return response.data
  });
  return res
}


async function isImplement() {
  let params = {
    projectNo: projectNo.value,
    // phaseId: 1,//立项前期 写死
    postIds: [16]//是否是施工人员
  }
  isImplementPer.value = await hasPermissonPost(params)
}


async function isSale() {
  let params = {
    projectNo: projectNo.value,
    // phaseId: 1,//立项前期 写死
    postIds: [2, 5, 6, 7]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  havePay.value = await hasPermisson(params)
  console.log("添加付款信息", havePay.value);

}


function getInfo(projectNo) {
  console.log("projectNoprojectNo", projectNo);

  let params = {
    projectNo: projectNo
  }


  //参与人
  listParticipan(params).then((response) => {
    console.log("参与人员", response);
    personList.value = response.data
  });

  //附件
  listAttachment(params).then((response) => {
    attachmentList.value = response.data;
  });

  //付款信息
  listPay(params).then((response) => {
    payList.value = response.data;
  });

  //核算信息
  listAccounting(params).then((response) => {
    accountingList.value = response.data;
  });

  //质保信息
  listWarranty(params).then((response) => {
    warrantyList.value = response.data;
  });

  listImplement(params).then((response) => {
    implementList.value = response.data;
  });


  listPhase(params).then((response) => {
    logs.value = response.data.list;

  });

  let currPhase = {
    projectNo: projectNo,
    phaseId: 1
  }


}

function getInitData() {
  loading.value = true;

  myAccountingList(queryParams.value).then((response) => {
    console.log("核算中的项目", response.data);
    notifyList.value = response.data;
    open1(notifyList.value)
  });

  myJoinProject(queryParamsCom.value).then((response) => {
    console.log("我参与的项目", response.data);
    completeList.value = response.data.rows;
    completeTotal.value = response.data.total;
  });

  getAssistList(queryParamsCom.value).then((response) => {
    console.log("配合项目", response.data);
    assistList.value = response.data.rows;
    assistTotal.value = response.data.total;
  });


  myProject(queryParams.value).then((response) => {
    console.log("我创建的项目", response.data);
    myList.value = response.data.rows;
    total.value = response.data.total;
  });

  needHandle(queryParamsneed.value).then((response) => {
    console.log("需我处理的项目", response.data);
    need.value = response.data.rows;
    needTotal.value = response.data.total;
  });


  auditList(null).then((response) => {
    console.log("待审核的往来客户", response.data);
    customerList.value = response.data
  });


  getMyListProcessing(queryParams.value).then((response) => {
    console.log("各个阶段信息", response.data);
    phaseDatas.value = response.data
  });


  loading.value = false;

  console.log("调用getInitData");

  getPermissionIndex(queryParams.value).then((response) => {
    indexPer.value = response
  });


}


function getListCom() {
  myJoinProject(queryParamsCom.value).then((response) => {
    console.log("已完成项目信息", response);
    completeList.value = response.data.rows;
    completeTotal.value = response.data.total;
  });
}


function handleSelectionChange(selection) {
  console.log("selection", selection);
  getListNeed()
}

function getListNeed() {
  needHandle(queryParamsneed.value).then((response) => {
    console.log("需我处理的项目", response.data);
    need.value = response.data.rows;
    needTotal.value = response.data.total;
  });
}

function getListCreate() {
  myProject(queryParams.value).then((response) => {
    console.log("我创建的项目", response.data);
    myList.value = response.data.rows;
    total.value = response.data.total;
  });
}

/** 查询绩效基本信息列表 */
function getList() {
  getInitData()
}

// getList()
getInitData()



// 所有可用列配置（可从接口获取）
const allColumns = [
  { label: "项目名称", prop: "projectName", visible: true },
  { label: "发起人", prop: "createUserName", visible: true },
  { label: "合同金额", prop: "contractAmount", visible: true },
  { label: "结算金额", prop: "settlementAmount", visible: true },
  { label: "项目阶段", prop: "phaseName", visible: true },
  { label: "立项日期", prop: "approvalDate", visible: true },
  { label: "上次更新时间", prop: "updateTime", visible: true },
  { label: "预计验收日期", prop: "acceptTime", visible: true },
  { label: "客户名称", prop: "customerName", visible: true },
  { label: "管家婆项目", prop: "housekeeperName", visible: true },
  { label: "项目类型", prop: "projectTypeName", visible: true },
  { label: "阶段确认人", prop: "joinPeople", visible: true },
  { label: "当前操作人", prop: "currentPeople", visible: true },

]

// 用户当前选择的列 props（由 el-checkbox-group 控制）
const selectedProps = ref([])

// 当前可见列列表（根据 selectedProps 排序后的结果）
const visibleColumns = computed(() => {
  return selectedProps.value
    .map(prop => allColumns.find(col => col.prop === prop))
    .filter(Boolean)
})



// 当前可见列（根据用户选择动态变化）
const selectedColumns = ref([...allColumns])


const saveColumnConfig = async () => {

  console.log('保存配置', selectedProps.value);
  // 调用保存到后端的接口

  await saveUserTableConfig({ configs: selectedProps.value, type: "home" })
  proxy.$modal.msgSuccess("保存配置成功");

}

const getWidth = (prop) => {
  switch (prop) {
    case 'projectName':
    case 'approvalDate':
    case 'updateTime':
    case 'acceptTime':
      return 200;
    case 'housekeeperName':
      return 300;
    default:
      return undefined;
  }
}

async function loadUserColumnConfig() {
  const res = await getUserTableConfig({ type: "home" })

  let defaultOrder = allColumns
    .filter(col => col.visible !== false) // 可以根据 visible 控制是否默认显示
    .map(col => col.prop)

  if (res.data && Array.isArray(res.data)) {
    // 使用用户保存的顺序（只保留合法的 prop）
    selectedProps.value = res.data.filter(prop =>
      allColumns.some(col => col.prop === prop)
    )
  } else {
    // 否则使用默认顺序
    selectedProps.value = defaultOrder
  }
}

import { h } from 'vue'
import { ElNotification } from 'element-plus'


onMounted(() => {
  //判断是否是手机端进入
  loadUserColumnConfig()
})

const open1 = (datas) => {

  for (let index = 0; index < datas.length; index++) {
    const element = datas[index];
    console.log("element.projectName", element.projectName);
  }

  if (datas?.length > 0) {
    // 拼接所有项目名为一个带换行的字符串（使用 <br>）
    //   let projectNamesHtml = datas.map(item => item.projectName).join('<br>');

    //   ElNotification({
    //   title: '通知',
    //   message: h('div', {
    //     style: {
    //       color: 'teal',
    //       whiteSpace: 'pre-line'
    //     },
    //     innerHTML: projectNamesHtml
    //   }),
    //   duration: 5000,
    //   customClass: 'my-custom-notification' // 自定义类名
    // });

    // 构建每个项目的截止日期信息
    const deadlineLines = datas.map(item => {
      const deadlineDate = new Date(item.createTime);
      deadlineDate.setDate(deadlineDate.getDate() + 30); // 添加30天
      const formattedDeadline = formatDate(deadlineDate);
      // return `${item.projectName} 截止日期：${formattedDeadline}`;
      return `${item.projectName} <span style="color: #666;">截止日期：</span><span style="color: red;">${formattedDeadline}</span>`;
    });

    // 拼接成 HTML 字符串
    // const notificationMessage = `以下项目已验收完成,如有报销费用未报销的请尽快报销<br>${deadlineLines.join('<br>')}`;
    // 设置提示语为黑色
    // 设置提示语为黑色
    const notificationMessage = `<span style="color: black;">以下项目已验收完成,如有报销费用未报销的请尽快报销</span>
${deadlineLines.join('<br>')}
`;

    // 创建通知
    ElNotification({
      title: '通知',
      message: h('div', {
        style: {
          color: 'teal',
          whiteSpace: 'pre-line',
          wordBreak: 'break-all'
        },
        innerHTML: notificationMessage
      }),
      duration: 8000,
      customClass: 'my-custom-notification'
    });


  }

}

function formatDate(date) {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

import useUserStore from '@/store/modules/user'

const userStore = useUserStore()


</script>

<style>
.my-custom-notification {
  max-width: 600px;
  width: auto;
}
</style>
